package org.vectrics.recruiter.struts.tag;

/**
 * @author Mike Moore
 */

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ecs.html.A;
import org.vectrics.SystemException;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Form;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.TextHelper;
import org.vectrics.common.pagelist.PageList;
import org.vectrics.common.util.DateSync;
import org.vectrics.common.util.StringUtils;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.job.Job;
import org.vectrics.recruiter.job.JobCandidate;
import org.vectrics.recruiter.job.JobCandidateCriteria;
import org.vectrics.recruiter.job.JobCandidateStatus;
import org.vectrics.recruiter.struts.admin.SaveJobAction;
import org.vectrics.recruiter.user.CandidateInfo;
import org.vectrics.recruiter.user.Interview;
import org.vectrics.struts.PageListTag;
import org.vectrics.user.Person;
import org.vectrics.user.PersonEncounterStatusType;




public class JobCandidateListTag extends PageListTag {
	public static final long serialVersionUID = 52258455;
	
    private transient final Log log = LogFactory.getLog(this.getClass());
    private String jobId = null;
    private boolean edit = false;
    //private RemoteUserProvider userManager = new RemoteUserProvider();
	//private JobManager jobManager = new JobManager();
	private Person authUser = null;
	private String width = "100%";
    

	@Override
	protected String getDescription() {
	    return(getPhrase("phrase.job.candidate.list.description"));
	}

	@Override
    protected String getPageListLink() {
   		return(getContextPath() + "/admin/jobs/candidate/index.do?jobId=" + jobId);
    }

	protected JobCandidateCriteria createCriteria() {
	    JobCandidateCriteria criteria = new JobCandidateCriteria();
	    
	    return(criteria);
	}
	
	@Override
	public PageList createPageList() {
	    
	    JobCandidateCriteria criteria = createCriteria();
	    if (this.getJobId() == null) {
	    	criteria.getOrderByList().add("dateAdded");
	    } else {
	    	criteria.getOrderByList().add("strength");
	    	//criteria.getOrderByList().add("candidateName");
	    }	    
	    if (jobId != null) {
	    	Job job = RecruitServiceLocator.getJobProvider().findJob(new Long(jobId));
	    	criteria.setJob(job);
	    }
	    criteria.setEndDate(DateSync.getCurrentTime());
	    
	    JobCandidatePageList pageList = new JobCandidatePageList(criteria);
	    return(pageList);
	}

	protected void showList(String str,	Cell listCell, List jobCandidates, Form form) {
		log.debug("doStartTag() called");
		//Properties formProperties = new Properties();
		//Properties invalidProperties = new Properties();
		try {
			authUser = this.getAuthPerson();
		}
		catch (Throwable ve) {
			log.error("Exception finding auth user", ve);
			throw new SystemException("Exception finding auth user", ve);
		}

		if ((jobId == null) || (jobId.trim().length() <= 0)) {
			log.debug("Job parameter was not specified, checking http session to see if current job registered");
			jobId = (String)this.getRequest().getParameter(SaveJobAction.CURRENT_JOB_KEY);
		}
		if ((jobId == null) || (jobId.trim().length() <= 0)) {
			log.debug("Job parameter was not specified, checking http session to see if current job registered");
			jobId = (String)this.getRequest().getSessionAttribute(SaveJobAction.CURRENT_JOB_KEY);
		}
		
		Job job = null;
		if (jobId == null) {
			log.debug("Error - jobId not specified, assuming candidates are for all jobs");
		}
		else {
			try {
				job = RecruitServiceLocator.getJobProvider().findJob(new Long(jobId));
			}
			catch (Exception de) {
				log.error("DataException finding job: id = " + jobId, de);
				throw new SystemException("DataException finding Job - id = " + jobId, de);
			}
			
			if (job == null) {
				log.error("Job not found, jobId = " + getJobId());
				throw new SystemException("Could not find job, id = " + getJobId());
			}			
			else {
				log.debug("found job");
			}
			
		}
		if (jobCandidates.size() > 0) {
			listCell.addElement(makeCandidateTable(jobCandidates, job).toString());
		}
		else {
			log.debug("no candidates found for this job");
		}
	}


	private Table makeCandidateTable(List candidates, Job job) {
		log.debug("makeCandidateTable() called");
		Table table = new BorderTable();
		table.setWidth(this.width);
		Row hdrRow = table.addRow();
        hdrRow.setDefaultBgImage(this.getContextPath() + "/site-graphics/tbl_hdr.gif");

		Cell hdrCell = hdrRow.addCell();
		hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Name"));
		//hdrCell.setClass("tableHdrBg");

		hdrCell = hdrRow.addCell(); 
		hdrCell.addElement(TextHelper.getFont("tableHdrFont", this.getPhrase("prompt.candidate.strength")));
		//hdrCell.setClass("tableHdrBg");

		hdrCell = hdrRow.addCell(); 
		hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Status"));
		//hdrCell.setClass("tableHdrBg");

		hdrCell = hdrRow.addCell(); 
		hdrCell.addElement(TextHelper.getFont("tableHdrFont", "Interviews"));
		//hdrCell.setClass("tableHdrBg");


		hdrCell = hdrRow.addCell();
		hdrCell.addElement(TextHelper.getFont("tableHdrFont", "&nbsp;"));
		//hdrCell.setClass("tableHdrBg");

		boolean canSelectCandidates = false;
		if (job != null)
			canSelectCandidates = authUser.hasDomainOrGlobalRole("job.select.candidates", job.getCompany().getDomain());
		else
			canSelectCandidates = authUser.hasDomainOrGlobalRole("job.select.candidates", null);
			
		if (canSelectCandidates) {
			hdrCell = hdrRow.addCell();
			hdrCell.addElement(TextHelper.getFont("tableHdrFont", "&nbsp;"));
		}
			
		
		
		Iterator iter = candidates.iterator();
		while (iter.hasNext()) {
			JobCandidate jobCand = (JobCandidate)iter.next();
			if (jobCand != null) {
				CandidateInfo candidate = jobCand.getCandidate();
				Person person = candidate.getPerson();
				
				Row dataRow = table.addRow();
				String name = person.getLastName() + ", " + person.getFirstName();
				if (person.getMiddleName() != null)
					name += " " + person.getMiddleName();
				String interviewStr = "";
				Collection interviews = RecruitServiceLocator.getJobProvider().findJobCandidateInterviews(jobCand);
				log.debug("interview list size = " + interviews.size());
				boolean hasInterviewed = false;
				boolean hasNeededInterview = false;
				boolean hasInterviewScheduled = false;
				boolean hasOverdueInterview = false;
				boolean hasBeenRejected = false;
				Collection<Interview> scheduledInterviews = new ArrayList<Interview>();
				if (interviews.size() > 0) {
					Iterator<Interview> interIter = interviews.iterator();
					while (interIter.hasNext()) {
						Interview interview = (Interview)interIter.next();
						String resultCode = interview.getStatusType().getCode();
						if (resultCode.equals(Interview.RESULT_FURTHER_INTERVIEW)) {
							hasInterviewScheduled = true;
							hasNeededInterview = true;
						} else if (resultCode.equals(PersonEncounterStatusType.STATUS_SCHEDULED)) {
							hasInterviewScheduled = true;
							scheduledInterviews.add(interview);
						} else if (resultCode.equals(Interview.RESULT_REJECTED)) {
							hasInterviewScheduled = true;
							scheduledInterviews.add(interview);
						} else {
							hasInterviewed = true;
						}
						if (hasInterviewScheduled && (interview.getDateStart().before(DateSync.getCurrentTime()))) {
							hasOverdueInterview = true;
						}
					}
				}
				else {
					hasInterviewed = false;
				}
				
				if (hasBeenRejected)
					interviewStr += "<font class=\"subFont\">" + this.getPhrase("interview.summary.rejected") + "</font><br>";
				if (hasOverdueInterview)
					interviewStr += "<font class=\"subFont\">" + this.getPhrase("interview.summary.has.overdue") + "</font><br>";
				if (hasNeededInterview)
					interviewStr += "<font class=\"subFont\">" + this.getPhrase("interview.summary.needs.schedule") + "</font><br>";
				if (hasInterviewed)
					interviewStr += "<font class=\"subFont\">" + this.getPhrase("interview.summary.has.interviewed") + "</font><br>";
				
				
				interviewStr = "<font class=\"subFont\"> &nbsp; " + interviewStr + "</font>";
				
				if (scheduledInterviews.size() > 0) {
					Table schedTable = new Table();
					schedTable.setWidth("100%");
					Iterator schedIter = scheduledInterviews.iterator();
					while (schedIter.hasNext()) {
						Interview interview = (Interview)schedIter.next();
						Row schedRow = schedTable.addRow();
						Cell cell = schedRow.addCell();
						cell.addElement(TextHelper.getFont("subFont", interview.getStatusType().getName()));
						cell = schedRow.addCell();
						cell.addElement(TextHelper.getFont("subFont", 
								CoreServiceLocator.getDateFormat().getDateFormatRoundToDay(this.getLocale())
									.format(interview.getDateStart())));
						cell = schedRow.addCell();
						if (interview.getLeadPerson() != null)
							cell.addElement(TextHelper.getFont("subFont", "w/" + interview.getLeadPerson().getName()));
					}
					interviewStr += schedTable.toString();
				}
	
				JobCandidateStatus currentStatus = jobCand.getCurrentStatus();
				String status = null;
				if (currentStatus == null) {
					status = "";
				} else {
					status = currentStatus.getStatusType().getDescription();
				}
	
				
				dataRow.addCell().addElement(TextHelper.getFont("subFont", name));
				dataRow.addCell().addElement(TextHelper.getFont("subFont", jobCand.getStrength().toString()));
				dataRow.addCell().addElement(TextHelper.getFont("subFont", status));
				
				if (StringUtils.isNullOrBlank(interviewStr))
					interviewStr = "&nbsp;";
				dataRow.addCell().addElement(TextHelper.getFont("subFont", interviewStr));
				Cell cell = dataRow.addCell();
				A link = new A();
				link.setHref(getContextPath() + "/admin/jobs/candidate/view/index.do?jobId=" 
							+ jobId + "&userId=" + person.getId() + "&jobCandidateId=" 
								+ jobCand.getId());
				link.setClass("subLink");
				link.addElement("details");
				cell.addElement(link);
				
	
				if (canSelectCandidates) {
					if (jobCand.getCurrentStatus().getStatusType().isEditable()) {
						cell = dataRow.addCell();
						link = new A();
						link.setHref(getContextPath() + "/admin/jobs/candidate/remove.do?jobCandidateId=" 
								+ jobCand.getId() + "&jobId=" + jobId);
						link.setClass("subLink");
						link.addElement("remove");
						cell.addElement(link);						
					} else {
						cell = dataRow.addCell();
						cell.addElement("&nbsp;");
					}
				}
			}
		}
		return(table);
	}


	/**
	 * @return
	 */
	public String getJobId() {
		return jobId;
	}

	/**
	 * @param jobId
	 */
	public void setJobId(String jobId) {
		this.jobId = jobId;
	}

	/**
	 * @return
	 */
	public boolean getEdit() {
		return edit;
	}

	/**
	 * @param edit
	 */
	public void setEdit(boolean edit) {
		this.edit = edit;
	}

	/**
	 * @return Returns the width.
	 */
	@Override
	public String getWidth() {
		return width;
	}

	/**
	 * @param width The width to set.
	 */
	@Override
	public void setWidth(String width) {
		this.width = width;
	}

}
